package com.bj58.ecdata.dashboard.service;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.bj58.ecdata.calc.dbservice.service.ClickService;
import com.bj58.ecdata.calc.dbservice.service.DisplayService;
import com.bj58.ecdata.calc.dbservice.service.InfoService;
import com.bj58.ecdata.calc.dbservice.service.TrackService;
import com.bj58.spat.scf.client.SCFInit;
import com.bj58.spat.scf.client.proxy.builder.ProxyFactory;
import com.bj58.wf.core.WF;

public class SCFClient {
	private final static Log log = LogFactory.getLog(SCFClient.class); // 日志

	/**
	 * SCF服务配置文件名
	 */
	private final static String SCF_CONFIG_FILE_NAME = "scf.config";
	/**
	 * 远程服务的连接缓存
	 */
	private static Map<Class<?>, Object> remoteServiceCache = new HashMap<Class<?>, Object>(); // 远程服务缓存
	private static volatile SCFClient instance = null; // 实例

	/**
	 * 私有的构造函数
	 */
	private SCFClient() {
		init();
	}

	/**
	 * 实例化
	 * 
	 * @author liujp
	 * @version 1.0
	 */
	public static final void initialSCF() {
		if (instance == null) {
			synchronized (SCFClient.class) {
				if(instance == null){
					instance = new SCFClient();
				}
			}
			
		}
	}

	/**
	 * 具体的初始化方法
	 * 
	 * @author liujp
	 * @version 1.0
	 */
	private void init() {

		initialSCFClient();

		remoteServiceCache.put(ClickService.class,
				ProxyFactory.create(ClickService.class, "tcp://DataService/ClickServiceImpl"));
		log.info("init ClickService success!!!");

		remoteServiceCache.put(DisplayService.class,
				ProxyFactory.create(DisplayService.class, "tcp://DataService/DisplayServiceImpl"));
		log.info("init DisplayService success!!!");

		remoteServiceCache.put(TrackService.class,
				ProxyFactory.create(TrackService.class, "tcp://DataService/TrackServiceImpl"));
		log.info("init TrackService success!!!");
		
//		remoteServiceCache.put(TrackService_TMP.class,
//				ProxyFactory.create(TrackService_TMP.class, "tcp://DataService/TrackServiceImpl_TMP"));
//		log.info("init TrackService_TMP success!!!");

		remoteServiceCache.put(InfoService.class,
				ProxyFactory.create(InfoService.class, "tcp://DataService/InfoServiceImpl"));
		log.info("init InfoService success!!!");

	}

	private void initialSCFClient() {
		log.info("init SCF start");
		String destPath = WF.getConfigFolder() + WF.getNamespace();
		String configPath = destPath + "/" + SCF_CONFIG_FILE_NAME;
		log.info("configPath=====" + configPath);
		SCFInit.init(configPath);
		log.info("init SCF success!!!");

	}

	/**
	 * 根据接口类型获取远程接口的服务
	 * 
	 * @author liujp
	 * @version 1.0
	 * @param 接口的class
	 *            <T>
	 * @param cls
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getRemoteService(Class<T> cls) {

		Object obj = remoteServiceCache.get(cls);
		if (obj != null) {
			return (T) obj;
		}
		return null;
	}

}
